package cn.bellychang.tdddemo.cl02refactor;

import java.util.ArrayList;

/**
 * @author: bellychang
 * @date: 2020/2/13
 */
public class PrimeUtil {

    public static final int BOUND = 2;

    /**
     * 编写一个函数，返回小于给定值max的所有素数组成的数组
     * Write a function that returns an array of all prime numbers less than the given value: max
     *
     * @param max
     * @return
     */
    public static int[] getPrimes(int max) {
        if (max <= BOUND) {
            return new int[]{};
        }
        ArrayList<Integer> result = new ArrayList<>();
        for (int value = 2; value < max; value++) {
            if (isPrime(value)) {
                result.add(value);
            }
        }
        return result.stream().mapToInt(i -> i).toArray();
    }

    private static boolean isPrime(int value) {
        for (int divider = 2; divider < value / 2 + 1; divider++) {
            if (value % divider == 0) {
                return false;
            }
        }
        return true;
    }
}
